package cn.hzh.forward.strategy.impl;

import cn.hzh.forward.config.properties.CosConfigProperties;
import com.qcloud.cos.COS;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @author 北渡
 * cos上传策略
 */
@Service("cosUploadStrategyImpl")
public class CosUploadStrategyImpl extends AbstractUploadStrategyImpl {

    @Autowired
    private CosConfigProperties cosConfigProperties;

    @Override
    public Boolean exists(String filePath) {
        return getCosClient().doesObjectExist(cosConfigProperties.getBucketName(), filePath);
    }

    @Override
    public void upload(String path, String fileName, InputStream inputStream) {
        getCosClient().putObject(cosConfigProperties.getBucketName(), path + fileName, inputStream, null);
    }

    @Override
    public String getFileAccessUrl(String filePath) {
        return cosConfigProperties.getUrl() + filePath;
    }

    private COS getCosClient() {
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        // 设置bucket所在的区域，比如广州(gz), 天津(tj)
        clientConfig.setRegion(new Region(cosConfigProperties.getRegion()));
        // 初始化秘钥信息
        COSCredentials cred = new BasicCOSCredentials(cosConfigProperties.getAccessKeyId(), cosConfigProperties.getAccessKeySecret());
        return new COSClient(cred, clientConfig);
    }

}
